<?php # Класс экспорта товаров

	Class Export_Product
	{
		private $page_titles = array();
		private $page_parents = array();
		private $fields = array();
		private $where = '1';
		private $with_service = '';
		private $sales_notes = array();
		private $descriptions = array();
		private $descriptions_products = array();
		private $page_id = '';
		
		private $file;
		
		function startExport( $date, $with_service = '' )
		{
			$this->conn = $GLOBALS['conn'];
			$this->elog = $GLOBALS['elog'];
			
			$this->with_service = $with_service ? $with_service : ( isset( $_POST['with_service'] ) ? $_POST['with_service'] : '' );
			
			$file_name = 'export_'.$date;
			$this->file = fopen( PATH_TO_FILES.'/'.PATH_TO_ARCHIVE_EXPORT_FILES_DIR.'/'.$file_name.'.csv', 'w');
			
			$this->getXmlData();
			
			$this->getSubCats();
			$this->getClauseParents();
			if( isset( $_POST['with_char'] ) )	
				$this->getCharactFields();
			$this->saveFielsNames();
			$this->saveProductData();

			return $file_name;
		}

		private function getSubCats()
		{
			$this->conn->unquery('SELECT `id`, `title`, `parents` FROM `pages` WHERE templ IN( "category", "sub_category" )');
			while( $page = $this->conn->fetch() )
			{
				$this->page_titles[$page->id] = $page->title;
				$this->page_parents[$page->id] = $page->parents.'#'.$page->id.'#';
			}
		}
		
		private function getClauseParents()		
		{
			$clause = $parents = $product_codes = $product_names = array();
			$i = 1;
			
			if( isset( $_FILES['csv_export_products']["error"] ) && $_FILES['csv_export_products']["error"] == 0 )
			{

				$file = fopen( $_FILES['csv_export_products']['tmp_name'], 'r' );
				while( ( $data = fgetcsv( $file , '' , ';' , '"' ) ) !== FALSE )
				{
					if( $i++ > 1 )
					{
						if( is_numeric( $data[0] ) )
							$product_codes[] = $data[0];
						elseif( isset( $data[1] ) && $data[1] )
							$product_names[] = '"'.mysql_real_escape_string( $data[1] ).'"';
					}
				}
				if(  count( $product_codes ) )
					$clause[] = '`p`.`product_code` IN( '.implode( ', ', $product_codes ).' )';
				if(  count( $product_names ) )
					$clause[] = '`p`.`name` IN( '.implode( ', ', $product_names ).' )';

			}
			elseif( isset( $_POST['export_cat'] ) )
			{
				foreach ( $_POST['export_cat'] as $id => $on )
					$parents[] = '"'.$this->page_parents[$id].'"';
				
				if( count( $parents ) ) {
					$clause[] = '`p`.`parents` IN( '.implode( ', ', $parents ).' )';
					if( count( $parents ) == 1 )
					{
						$this->page_id = array_shift( array_flip( $_POST['export_cat'] ) );  // Вытащить ID категории
					}
				}
			}

			
			if( count( $clause ) )
				$this->where = implode( ' OR ', $clause );
		}
		
 		private function getCharactFields()
		{
			if( $this->page_id )
			{
				$this->conn->query('SELECT `f`.`id`, `f`.`name` FROM `store_p_charact_fields` AS `f`
										JOIN `store_p_charact_datas` AS `d` ON `d`.`field_id` = `f`.`id`
										JOIN `store_products_cache` AS `p` ON `p`.`product_code` = `d`.`product_code`
										LEFT JOIN `store_p_charact_fields_sort` AS `s` ON `s`.`field_id` = `d`.`field_id` AND s.page_id = '.$this->page_id.'
											WHERE '.$this->where.'
												GROUP BY `f`.`id`
													ORDER BY COALESCE (`s`.`zin`, 999999999)');
			}
			else
			{
				$this->conn->query('SELECT DISTINCT `f`.`id`, `f`.`name` FROM `store_p_charact_fields` AS `f`
										INNER JOIN `store_p_charact_datas` AS `d` ON `d`.`field_id` = `f`.`id`
											INNER JOIN `store_products_cache` AS `p` ON `p`.`product_code` = `d`.`product_code`
												WHERE '.$this->where );
			}
			while( $field = $this->conn->fetch() )
				$this->fields[$field->id] = $field->name;
		}
		
		private function saveFielsNames()
		{
			$fieldNames = array	(
							'Код', 
							'Главная категория', 
							'Конечная категория', 
							'Префикс', 
							'Марка', 
							'Название', 
							'Цена',
							'ПП',
							'Габаритность',
						);
						
			$servises = array(
							'ПМ',
							'ПД',
							'БИД',
							'ЦБИД',
							'Стоимость монтажа',
							'Стоимость vip',
							'Хиты',
							'Новинки',
							'Распродажа',
							'Аксессуары',
							'Похожие товары',
							'Код корсини',
							'Код Маркета',
							'Наименование маркета',
							'Стоимость доставки',
							'sales_notes',
							'url',
							'description'
						);
			
			if( $this->with_service )
				$fieldNames = array_merge( $fieldNames, $servises );
			
			
			
			foreach ( $fieldNames as $fieldName )  
				$fieldName_arr[] = $fieldName;
			
			foreach( $this->fields as $field )
				$fieldName_arr[] = $field;
			
			fputcsv( $this->file, $fieldName_arr,  ';' );
			
			unset( $fieldName_arr );
		}
		
		function getXmlData()
		{
			$this->conn->query('SELECT * FROM `store_product_xml_data` WHERE type in("sales_notes", "description")');
			while( $row = $this->conn->fetch() ) {
				if($row->type == "sales_notes")
					$this->sales_notes[$row->id] = $row->value;
				elseif($row->type == "description")
					$this->descriptions[$row->id] = $row->value;
			}


            $sales_notes_id = array_keys($this->sales_notes);
            $sales_notes_id_string = implode(', ', $sales_notes_id);

			$descriptions_id = array_keys($this->descriptions);
			$descriptions_id_string = implode(', ', $descriptions_id);

			$this->conn->query("SELECT * FROM `store_product_xml_data_relation` where xml_data_id in({$sales_notes_id_string})");
			while( $row = $this->conn->fetch() )
				$this->sales_notes_products[$row->product_code] = $row->xml_data_id;

			$this->conn->query("SELECT * FROM `store_product_xml_data_relation` where xml_data_id in({$descriptions_id_string})");
			while( $row = $this->conn->fetch() )
				$this->descriptions_products[$row->product_code] = $row->xml_data_id;
		}
		
		private function saveProductData()
		{
			global $COST_OF_DELIVERY_1;
			$characts = array();
			
			if( isset( $_POST['with_char'] ) )
			{
				$this->conn->query('SELECT `p`.`product_code`, `d`.`field_id`, `v`.`value` FROM `store_p_charact_datas` AS `d`
										INNER JOIN `store_products_cache` AS `p` ON `p`.`product_code` = `d`.`product_code`
											INNER JOIN `store_p_charact_values` AS `v` ON `v`.`id` = `d`.`value_id`
												WHERE '.$this->where );
							
				while( $charact = $this->conn->fetch() )
					$characts[$charact->product_code][$charact->field_id] = $charact->value;
			}
			
			
			$this->conn->unquery('SELECT p.*, c.url  FROM `store_products_view` AS `p`
			                        left join store_products_cache c on p.product_code = c.product_code
			                        WHERE '.$this->where.' ORDER BY `parents`, `prefix`, `brand`, `product_code`, `name`' );
					
			while( $product = $this->conn->fetch() )
			{

				$main_page_id = array_shift( getIdsArr( $product->parents ) );
				$page_id = array_pop( getIdsArr( $product->parents ) );
				
				$sales_notes = isset( $this->sales_notes_products[$product->product_code] ) ?
								( isset( $this->sales_notes[$this->sales_notes_products[$product->product_code]] ) ?
									$this->sales_notes[$this->sales_notes_products[$product->product_code]] : '' ) : '';

				$descriptions = isset( $this->descriptions_products[$product->product_code] ) ?
					( isset( $this->descriptions[$this->descriptions_products[$product->product_code]] ) ?
						$this->descriptions[$this->descriptions_products[$product->product_code]] : '' ) : '';
				
				$csv_fields = array(
					$product->product_code,
					$this->page_titles[$main_page_id],
					$this->page_titles[$page_id],
					$product->prefix,
					$product->brand,
					$product->name,
					(int)$product->price_retail,
					$product->pp,
					$product->volume,
				);
					
				$servises = array( 
					$product->pm,
					$product->pd,
					$product->bid,
					$product->cbid,
					$product->price_inst,
					$product->price_vip,
					$product->hit,
					$product->new,
					$product->sale,
					$product->accessories,
					$product->similar,
					$product->corsini_code,
					$product->market_code,
					$product->market_name,
					isset( $COST_OF_DELIVERY_1[$product->volume] ) ? $COST_OF_DELIVERY_1[$product->volume] : '',
					$sales_notes,
                    	HOST_NAME .'/'.$product->url,
					$descriptions
				);
				
				
				if( $this->with_service )
					$csv_fields = array_merge( $csv_fields, $servises );

					
				if( isset( $_POST['with_char'] ) )
					foreach( $this->fields as $field_id => $value )
						$csv_fields[] = isset( $characts[$product->product_code][$field_id] ) ? $characts[$product->product_code][$field_id] : '';


				fputcsv( $this->file, $csv_fields, ';' );
			}
			fclose( $this->file );
		}
	}